package osami.communication;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * TCPIPAddress class represents a TCP/IP address
 * 
 * @author osami
 *
 */
public class TCPIPAddress implements Address
{
	String iAddress = null;
	
	/** 
	 * Creates a new instance of TCPIPAddress with the given address.
	 * 
	 * @param aAddress
	 */
	public TCPIPAddress( String aAddress )
	{
		iAddress = aAddress;
	}
	
	/**
	 * returns the IP address as a String
	 */
	public String toString()
	{
		return iAddress;
	}

	/**
	 * Compares the given address to this address and returns the result as a boolean
	 * 
	 * @param aAddress
	 * @return boolean
	 */
	public boolean equals( Address aAddress )
	{
		boolean equals = aAddress.toString().contentEquals( iAddress );
		//System.out.println( "Comparing: "+ aAddress + " to: " + iAddress + " -> " + equals );

		return equals;
	}
	
	/**
	 * Compares this address hostname to all hostnames of existing interfaces and returns the result as a boolean.
	 * Returns true if address hostname equals with a hostname in an interface.
	 * Returns false if no match is found.
	 * 
	 * @return boolean
	 */
	public boolean equals ()
	{
		String compHostName1;
		String compHostName2 = getHostName();
		Enumeration<NetworkInterface> nifs = null;
		try {
			nifs = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		while (nifs.hasMoreElements()) {
			NetworkInterface nif = nifs.nextElement();
			
			Enumeration<InetAddress> inetAddresses = nif.getInetAddresses();
			
			while(inetAddresses.hasMoreElements()) {
				InetAddress inetAddr = inetAddresses.nextElement();
				compHostName1 = inetAddr.getCanonicalHostName();
				//System.out.println("Comparing: " + compHostName1 + " to: " + compHostName2);
				if (compHostName1.contentEquals(compHostName2)) 
					return true;
			}
			
		}
				
		return false;
	}
	
	/**
	 * Returns the hostname of this address as a string.
	 * 
	 * @return String
	 */
	public String getHostName()
	{
		try
		{
			return InetAddress.getByName( iAddress ).getHostName();
		}
		catch ( UnknownHostException e )
		{
		}
		
		return iAddress;
	}
}
